#include <iostream>
#include <string>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "Thread.hpp"
using namespace std;
int sockfd = 0;
string server_ip;
uint16_t server_port = 0;
pthread_t id;

using namespace ThreadModlue;
void Send()
{
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(server_port);
    server.sin_addr.s_addr=inet_addr(server_ip.c_str());

    const string online="inline";
    sendto(sockfd,online.c_str(),online.size(),0,(struct sockaddr*) &server,sizeof(server));

    while(true)
    {
        string input;
        cout<<"Please Enter#";
        getline(cin,input);
        int n=sendto(sockfd,input.c_str(),input.size(),0,(struct sockaddr*)&server,sizeof(server));
        if(input=="QUIT")
        {
            pthread_cancel(id);
            break;
        }
    }
}
void Recv()
{
    while(true)
    {
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len =sizeof(peer);
        int m=recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);
        if(m>0)
        {
            buffer[m]=0;
            cout<<buffer<<endl;
        }
    }
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cerr << "Usage" << argv[0] << "server_ip and server_port" << endl;
    }
    server_ip = argv[1];
    server_port = stoi(argv[2]);
    sockfd =socket(AF_INET,SOCK_DGRAM,0);
    if(socket<0)
    {
        cerr<<"socket error"<<endl;
        exit(2);
    }

    Thread recver(Recv);//负责接收数据的线程
    Thread sender(Send);

    recver.Start();
    sender.Start();

    id=recver.Id();
    recver.Join();
    sender.Join();

    return 0;
}